using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Phoenix.Diagnostics;
using Phoenix.Frames;

namespace Phoenix
{
    public abstract class PhoenixApplicationHostTarget : Application, IPhoenixHostTarget
    {
        Window shell;

        /*********************
         * 
         * We are handling the app startup inside the PhoenixApplicationHostTarget, 
         * so we want to hide both startup and StartupUri from the end App.xaml
         * 
         ********************/

        protected PhoenixApplicationHostTarget()
        {
            TaskScheduler.UnobservedTaskException += TaskSchedulerUnobservedTaskException;
        }

        void TaskSchedulerUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            if (e.Observed) return;

            e.SetObserved();
            Trace.WriteError(this, () => "Unobserved task exception", exception:e.Exception.Flatten());
        }

        protected abstract Task<IPhoenixHost> InitialisePhoenix();
        protected IPhoenixHost Host { get; set; }

        protected virtual Window CreateShell(INavigationFrame navigationFrame)
        {
            return new Window
                {
                    Content = navigationFrame
                };
        }

        public void Show(INavigationFrame navigationFrame)
        {
            NavigationFrame = navigationFrame;
            shell = CreateShell(navigationFrame);
            shell.Show();
        }

        public INavigationFrame NavigationFrame { get; private set; }

        /// <summary>
        /// The ContentHost (Window, UserControl etc which hosts the NavigationFrame)
        /// </summary>
        public Control ContentHost
        {
            get { return shell; }
        }
    }
}